<template>
    <div>
        <el-card style="height: 80px;">
            <el-form :inline="true" size="normal" class="form">
                <el-form-item label="用户名:">
                    <el-input style="width: 300px;" placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item label="" size="normal">
                    <el-button type="primary" size="default" @click="search" :disabled="keyword?false:true">搜索</el-button>
                    <el-button type="primary" size="default" @click="reset">重置</el-button>
                </el-form-item>

            </el-form>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
            <el-button type="primary" size="default" @click="deleteSelectUser"
                :disabled="selectIdArr.length > 1 ? false : true">批量删除</el-button>

            <el-table border stripe style="margin: 10px 0px;" :data="userArr" @selection-change="selectChange">
                <el-table-column type="selection" align="center">
                </el-table-column>
                <el-table-column label="#" type="index" width="50px" align="center">
                </el-table-column>
                <el-table-column label="ID" align="center" prop="id">
                </el-table-column>
                <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="操作" width="300px" align="center">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                        <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                        <el-popconfirm :title="`你确定删除${row.username}吗?`" @confirm="deleteUser(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->

            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
                :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total"
                @size-change="handler" @current-change="getHasUser" />
            <!--抽屉  -->
            <!-- 添加用户抽屉 -->
            <el-drawer v-model="drawer">
                <template #header>
                    <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
                </template>
                <template #default>
                    <div>
                        <el-form :model="userParams" :rules="rules" label-width="80px" :inline="false" size="normal"
                            ref="formRef">
                            <el-form-item label="用户姓名" prop="username">
                                <el-input placeholder="请您输入用户姓名" v-model="userParams.username"></el-input>
                            </el-form-item>
                            <el-form-item label="用户昵称" prop="name">
                                <el-input placeholder="请您输入用户昵称" v-model="userParams.name"></el-input>

                            </el-form-item>
                            <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                                <el-input placeholder="请您输入用户密码" v-model="userParams.password"></el-input>
                            </el-form-item>
                        </el-form>

                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="save">确定</el-button>
                    </div>
                </template>
            </el-drawer>
            <!-- 编辑用户抽屉 -->
            <el-drawer v-model="drawer1">
                <template #header>
                    <h4>分配角色(职位)</h4>
                </template>
                <template #default>
                    <div>
                        <el-form label-width="80px" :inline="false" size="normal">
                            <el-form-item label="用户姓名">
                                <el-input v-model="userParams.username"></el-input>
                            </el-form-item>
                            <el-form-item label="职位列表">
                                <el-checkbox @change="handleCheckAllChange" v-model="checkAll"
                                    :indeterminate="isIndeterminate">全选</el-checkbox>
                                <el-checkbox-group @change="handleCheckedCitiesChange" v-model="userRole">
                                    <!-- label 是要收集的数据 v-model="userRole"是收集到的地方-->
                                    <el-checkbox v-for="(role, index) in allRole" :key="role.id" :label="role">
                                        {{ role.roleName }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-form>

                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="drawer1 = false">取消</el-button>
                        <el-button type="primary" @click="confirmClick">确定</el-button>
                    </div>
                </template>
            </el-drawer>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { reqAddOrUpdateUser, reqUserInfo, reqAllRole, reqSetUserRole, reqRemoveUser ,reqSelectUser} from '@/api/acl/user';
import type { UserResponseData, Records, User, AllRole, SetRoleData } from '@/api/acl/user/type';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

// 分页器码数
let pageNo = ref<number>(1);
// 分页器一页条数
let pageSize = ref<number>(5);
// 总条数
let total = ref<number>(0);
let drawer = ref<boolean>(false);
let drawer1 = ref<boolean>(false);
//存储全部用户的数组
let userArr = ref<Records>([]);
//收集用户信息的响应式数据
let userParams = reactive<User>({
    username: '',
    name: '',
    password: ''
});
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<User[]>([]);
// 获取form组件实例
let formRef = ref<any>();
// 收集全部职位
let allRole = ref<AllRole>([]);
// 已选的职位
let userRole = ref<AllRole>([]);
// 收集搜索框数据
let keyword=ref<string>('');
// 获取仓库
//获取模板setting仓库
let settingStore = useLayOutSettingStore();
// 添加用户按钮的回调函数
const addUser = async () => {

    drawer.value = true;
    // 清空数据
    Object.assign(userParams, {
        username: '',
        name: '',
        password: '',
        id: 0
    })
    // 清除错误信息
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('password');
    })
}
//  获取数据
onMounted(() => {
    // 没有传参默认第一页
    getHasUser();
})
//获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
    pageNo.value = pager;
    let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value,keyword.value);
    if (result.code == 200) {
        total.value = result.data.total;
        userArr.value = result.data.records;
    }
}
const handler = () => {
    getHasUser();
}
// 编辑用户按钮触发的回调函数
const updateUser = (row: any) => {
    drawer.value = true;
    // 收集用户数据
    // 两个对象结合
    Object.assign(userParams, row);

    //清除上一次的错误的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
    });
}
// 添加或更新用户抽屉的确定按钮的回调函数
const save = async () => {
    //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
    await formRef.value.validate()
    //保存按钮:添加新的用户|更新已有的用户账号信息
    let result: any = await reqAddOrUpdateUser(userParams);
    //添加或者更新成功
    if (result.code == 200) {
        //关闭抽屉
        drawer.value = false;
        //提示消息
        ElMessage({ type: 'success', message: userParams.id ? '更新成功' : '添加成功' });
        //获取最新的全部账号的信息
        // getHasUser(userParams.id ? pageNo.value : 1);
        //浏览器自动刷新一次
        window.location.reload();
    } else {
        //关闭抽屉
        drawer.value = false;
        //提示消息
        ElMessage({ type: 'error', message: userParams.id ? '更新失败' : '添加失败' });
    }
}
// 添加或更新用户抽屉的取消按钮的回调函数
const cancel = () => {
    // 关闭抽屉
    drawer.value = false;
}
// 表单检验规则字段
// required:true--这个字段务必要进行校验
// trigger:'blur'校验的时间==失去焦点
// validator自定义校验规则
// 校验用户名字的回调函数 rule：规则对象 value：表单元素的文本内容 callBack 回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户名字至少五位'))
    }

}
const validatorname = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户昵称至少五位'))
    }

}
const validatorPassword = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 6) {
        callBack();
    } else {
        callBack(new Error('用户密码至少六位'))
    }
}

const rules = {
    // 用户名字
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    // 用户名称
    name: [{ required: true, trigger: 'blur', validator: validatorname }],
    //用户的密码
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
// 分配角色按钮的回调函数
const setRole = async (row: User) => {
    // 收集用户角色数据
    Object.assign(userParams, row)
    let result = await reqAllRole((userParams.id as number));
    if (result.code == 200) {
        // 获取全部职位角色
        allRole.value = result.data.allRolesList;
        // 获取用户的当前角色
        userRole.value = result.data.assignRoles
        drawer1.value = true;
    }


}
//收集顶部复选框全选数据
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
// 全选按钮触发的回调事件
const handleCheckAllChange = (val: boolean) => {
    //val(复选框状态):true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : [];
    isIndeterminate.value = false;//关闭不确定样式
}
//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    // console.log(value.length);
    // if(value.length==allRole.value.length){
    //     checkAll.value=true;
    //     isIndeterminate.value=false;
    // }else{
    //     checkAll.value=false;
    // }
    //顶部复选框的勾选数据
    //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    // 明确写法 checkAll.value = (value.length === allRole.value.length) ? true : false;
    // 明确写法isIndeterminate.value = (value.length !== allRole.value.length);

    checkAll.value = value.length === allRole.value.length
    isIndeterminate.value = value.length !== allRole.value.length
}
// 确定按钮的回调函数
const confirmClick = async () => {
    let data: SetRoleData = {
        userId: (userParams.id as number),
        // 遍历数组return id 赋值给roleIdlist
        roleIdList: userRole.value.map(item => {
            return (item.id as number)
        })
    }
    let result = await reqSetUserRole(data);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '分配职务成功'
        })
        drawer1.value = false;
        getHasUser(pageNo.value);

    } else {
        ElMessage({
            type: 'success',
            message: '分配职务成功'
        })
        drawer1.value = false;
    }
}
// 删除用户按钮触发的回调函数
const deleteUser = async (userId: number) => {
    let result: any = await reqRemoveUser(userId);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}
// 表格复选框发生变化触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value;
}
// 批量删除按钮触发的回调
const deleteSelectUser =async () => {
    // 过滤数组，得到id数组
    let idsList:any =selectIdArr.value.map(item=>{
        return item.id
    })
    let result:any=await reqSelectUser(idsList);
    if(result.code==200){
        ElMessage({type:'success',message:'删除成功'});
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }else{
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
    
}
// 搜索按钮触发的回调函数
const search=()=>{
    getHasUser();
    keyword.value=''
}
// 重置按钮的回调函数
const reset=()=>{
    settingStore.refsh=!settingStore.refsh;
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    /**子元素）在主轴（默认为水平方向）上的对齐方式。 */
    align-items: center;
    /**center的值意味着所有的项目将在交叉轴方向上居中对齐,项目将在垂直方向上居中对齐。 */
}
</style>